package com.example.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.ApiResult;
import com.example.entity.Resource;
import com.example.mapper.ResourceMapper;
import com.example.service.ResourceService;
import com.example.utils.PageResult;
import com.example.vo.ResourceVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {
    @javax.annotation.Resource
    private ResourceMapper resourceMapper;

    @Value("${web.windows.upload-path}")
    private String windowsSavePath;


    @Value("${web.linux.upload-path}")
    private String linuxSavePath;


    @javax.annotation.Resource
    private Environment env;

    public ApiResult uploadAvatarMp4(@RequestParam(required = false, value = "upFile") MultipartFile upFile, String baseUrl){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        if(upFile.isEmpty()) {
            return ApiResult.fail("您未选择任何文件！");
        }
        else {
            // 获取上传的文件名称，并结合存放路径，构建新的文件名称
            String originalFileName = upFile.getOriginalFilename();
            // 获取文件扩展名，扩展名不带“.”
            String fileSuffix = FileUtil.extName(originalFileName);

            String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + fileSuffix;
            //限制文件类型
            if (! ( fileSuffix.equals("mp4") || fileSuffix.equals("avi") )) {
                return ApiResult.fail("仅支持上传.mp4、.avi视频格式！");
            }
            // 获取操作系统名称
            String osName = env.getProperty("os.name");
            File saveFile  = null;
            String format = sdf.format(new Date());
            if(osName.contains("Windows")) {
                saveFile = new File(windowsSavePath + format);
            }
            else {
                saveFile = new File(linuxSavePath + format);
            }
            // 如果服务器保存文件目录不存在，则创建
            if(saveFile != null && !saveFile.exists()) {
                saveFile.mkdirs();
            }
            try {
                upFile.transferTo(new File(saveFile,newFileName));
                String imgUrl = baseUrl+"resource/"+ format + newFileName; // 客户端访问头像路径，也就是存储在数据库中路径
                return ApiResult.ok(imgUrl,"视频上传成功！");
            } catch (IOException e) {
                return ApiResult.fail("上传视频失败！");
            }
        }
    }

    public ApiResult uploadAvatarJpg(String baseUrl, @RequestParam(required = false, value = "upFile") MultipartFile upFile){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        if(upFile.isEmpty()) {
            return ApiResult.fail("您未选择任何文件！");
        }
        else {
            // 获取上传的文件名称，并结合存放路径，构建新的文件名称
            String originalFileName = upFile.getOriginalFilename();
            // 获取文件扩展名，扩展名不带“.”
            String fileSuffix = FileUtil.extName(originalFileName);

            String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + fileSuffix;
            //限制文件类型
            if (! ( fileSuffix.equals("jpg") || fileSuffix.equals("gif") )) {
                return ApiResult.fail("仅支持上传.jpg、.gif图片格式！");
            }
            // 获取操作系统名称
            String osName = env.getProperty("os.name");
            File saveFile  = null;
            String format = sdf.format(new Date());
            if(osName.contains("Windows")) {
                saveFile = new File(windowsSavePath + format);
            }
            else {
                saveFile = new File(linuxSavePath + format);
            }
            // 如果服务器保存文件目录不存在，则创建
            if(saveFile != null && !saveFile.exists()) {
                saveFile.mkdirs();
            }
            try {
                upFile.transferTo(new File(saveFile,newFileName));
                String imgUrl = baseUrl+"resource/"+ format + newFileName; // 客户端访问头像路径，也就是存储在数据库中路径
                return ApiResult.ok(imgUrl,"视频上传成功！");
            } catch (IOException e) {
                return ApiResult.fail("上传视频失败！");
            }
        }
    }


    @Override
    public Integer addResource(String resourceTitle, MultipartFile resourceUrl, MultipartFile picUrl, Integer majorId) {
        ApiResult apiResult = uploadAvatarMp4(resourceUrl, null);
        ApiResult apiResult1 = uploadAvatarJpg(null, picUrl);
        if (apiResult.isSuccess() == true && apiResult1.isSuccess()) {
            String resourceUrlDate = (String) apiResult.getData();
            String picUrlDate = (String) apiResult1.getData();
            Integer integer = resourceMapper.addResource(resourceTitle, resourceUrlDate, picUrlDate, majorId);
            return integer;
        }
        return null;
    }

    @Override
    public Integer updateResource(HttpServletRequest request,Integer id, String resourceTitle, MultipartFile resourceUrl, MultipartFile picUrl, Integer majorId) {
        String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + request.getContextPath();
        ApiResult apiResult = uploadAvatarMp4(resourceUrl,baseUrl);
        ApiResult apiResult1 = uploadAvatarJpg(baseUrl,picUrl);
        if (apiResult.isSuccess() == true && apiResult1.isSuccess()) {
            String resourceUrlDate = (String) apiResult.getData();
            String picUrlDate = (String) apiResult1.getData();
            Integer integer = resourceMapper.updateResource(id , resourceTitle, resourceUrlDate, picUrlDate, majorId);
            return integer;
        }
        return null;
    }

    /**
     * 根据专业id查找所需信息
     * @param majorId
     * @param page
     * @param limit
     * @return
     */
    @Override
    public PageResult<List<ResourceVO>> selectResource(Integer majorId, Integer page, Integer limit) {
        PageResult<List<ResourceVO>> pageResult = new PageResult<>();
        //启动分页
        PageHelper.startPage(page,limit,true);

        List<ResourceVO> resourceVOList = resourceMapper.selectResource(majorId,page,limit);

        PageInfo<ResourceVO> pageInfo = new PageInfo<>(resourceVOList);
        pageResult.setPages(pageInfo.getPages());
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setPageNum(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setList(pageInfo.getList());
        return  pageResult;
    }

    @Override
    public Page<Resource> Page(Integer page, Integer size) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_date");
        Page<Resource> resourcePage = new Page<>(page, size);
        Page page1 = resourceMapper.selectPage(resourcePage, queryWrapper);
        return page1;
    }







 /*   @Override
    public Page<ResourceVO> Page(Integer page, Integer size) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_date");
        Page<Resource> resourcePage = new Page<>(page, size);
        Page page1 = resourceMapper.selectPage(resourcePage, queryWrapper);

        List<Resource> records = page1.getRecords();

        for (Resource r : records) {
            Major major = majorMapper.selectById(r.getMajorId());
            queryWrapper.eq("major_id", major);
            r.setMajor(major);
        }
        for (Resource r : records) {
            ResourceVO resourceVO = new ResourceVO();
            resourceVO.setResourceTitle(r.getResourceTitle());
            resourceVO.setMajorName(r.getMajor().getMajorName());
            resourceVO.setPicUrl(r.getPicUrl());
            resourceVO.setResourceUrl(r.getResourceUrl());
        }

        return page1;
    }*/
}
